package com.itheima.app.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.app.exception.BusinessException;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Sound;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.SoundService;
import com.itheima.vo.SoundVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;
import java.util.Date;
import java.util.List;

@Component
public class SoundManager {

    @DubboReference
    private SoundService soundService;

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer server;

    @DubboReference
    private UserInfoService userInfoService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //发送语音(保存)
    public void saveSound(MultipartFile soundFile) throws IOException {
        //1.获取当前登录用户
        Long userId = UserHolder.get().getId();

        //2.在redis中设置当天上传中的次数为10次
        //2.1获取当天日期
        String today = DateUtil.formatDate(new Date());
        //2.2拼接key
        String key = userId+"_"+"send_sound"+"_"+today;
        //2.3获取数据进行判断(remainingTimes为当天剩余次数)
        String remainingTimes = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isEmpty(remainingTimes)) {
            //当天没有上传语音
            stringRedisTemplate.opsForValue().set(key,"9", Duration.ofDays(1));
        }else if (remainingTimes.equals("0")){
            //次数用完
            throw new BusinessException("今日次数已用完,请明日再来");
        }else {
            //如果value有值则自减1
            stringRedisTemplate.opsForValue().decrement(key);
        }

        //3.上传文件到fastDFS
        StorePath storePath = client.uploadFile(soundFile.getInputStream(), soundFile.getSize(), FileUtil.extName(soundFile.getOriginalFilename()), null);
        String fullPath = storePath.getFullPath(); //文件id
        String webServerUrl = server.getWebServerUrl();


        //3.封装对象,存到mongo中
        Sound sound = new Sound();
        sound.setUserId(userId);
        sound.setGender(userInfoService.findByUserId(userId).getGender());
        sound.setSoundUrl(webServerUrl+fullPath);

        soundService.saveSound(sound);
    }

    //随机获取一条语音
    public ResponseEntity getSound() {
        //1.获取当前登录的用户id
        Long userId = UserHolder.get().getId();

        //2.判断当前用户的登录次数是否耗尽
        //2.1获取当天日期
        String today = DateUtil.formatDate(new Date());
        //2.2拼接key
        String key = userId+"_"+"get_sound"+"_"+today;
        String remainingTimes = stringRedisTemplate.opsForValue().get(key);

        if (StrUtil.isEmpty(remainingTimes)) {
            //当天没有接收语音
            stringRedisTemplate.opsForValue().set(key,"9", Duration.ofDays(1));
        }else if (remainingTimes.equals("0")){
            //次数用完
            throw new BusinessException("今日次数已用完,请明日再来");
        }else {
            //如果value有值则自减1
            stringRedisTemplate.opsForValue().decrement(key);
        }

        //3.调用service进行查询
        List<Sound> sounds = soundService.receiveSound(userId,userInfoService.findByUserId(userId).getGender());
        //3.1判断sounds是否为空
        SoundVo vo = null;
        if (CollUtil.isNotEmpty(sounds)) {
            //3.1.1遍历集合
            for (Sound sound : sounds) {
                //获取userInfo信息
                UserInfo userInfo = userInfoService.findByUserId(sound.getUserId());
                //新建soundVo
                vo = new SoundVo();
                vo.setAvatar(userInfo.getAvatar());
                vo.setNickname(userInfo.getNickname());
                vo.setGender(userInfo.getGender());
                vo.setAge(userInfo.getAge());
                vo.setSoundUrl(sound.getSoundUrl());

                String value = stringRedisTemplate.opsForValue().get(key);
                Integer count = Integer.valueOf(value);
                vo.setRemainingTimes(count);
            }
        }



        return ResponseEntity.ok(vo);
    }
}
